import logging
import os
import sys
import schedule
import yaml


def load_config(path):
    if not os.path.isfile(path):
        logging.error(f"配置文件不存在: {path}")
        sys.exit(1)

    with open(path, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)

# 解析 schedule 字符串并注册任务
def setup_schedule(config, task_func):
    server_conf = config['server']
    schedule_str = server_conf['schedule']
    if schedule_str.endswith('min'):
        minutes = int(schedule_str.replace('min', ''))
        schedule.every(minutes).minutes.do(task_func, config=config)
    elif schedule_str.endswith('sec'):
        seconds = int(schedule_str.replace('sec', ''))
        schedule.every(seconds).seconds.do(task_func, config=config)
    elif schedule_str.endswith('h'):
        hours = int(schedule_str.replace('hour', ''))
        schedule.every(hours).hours.do(task_func, config=config)
    else:
        raise ValueError(f"不支持的 schedule 格式：{schedule_str}")
    return schedule_str